﻿using System;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.ComponentModel;
using System.Drawing.Design;
using System.Reflection;
using UtfprLibrary.EntityFramework.ComponentModel;

namespace UtfprLibrary.Windows.Forms.ComponentModel {
    /// <summary>
    /// 
    /// </summary>
    internal class UtfprEagerLoadEditor : UITypeEditor {
        /// <summary>
        /// Displays an ellipsis (...) button to start a modal dialog box.
        /// </summary>
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) {
            return UITypeEditorEditStyle.Modal;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="provider"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) {
            if (provider != null) {
                IWindowsFormsEditorService editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
                if (editorService != null) {
                    UtfprBindingNavigatorBase controlValue = null;

                    //se for pela smart-tag
                    if (context.Instance.GetType() == typeof(UtfprBindingNavigatorActionList)) {
                        var actionList = (UtfprBindingNavigatorActionList)context.Instance;
                        var flags = BindingFlags.Instance | BindingFlags.NonPublic;
                        var control = actionList.GetType().GetField("LinkedControl", flags);
                        controlValue = (UtfprBindingNavigatorBase)control.GetValue(actionList);                          
                    } else if (context.Instance.GetType() == typeof(UtfprBindingNavigatorBase)) {
                        controlValue = (UtfprBindingNavigatorBase)context.Instance;
                    }

                    if (controlValue != null && controlValue.FetchMode == FetchModeEnum.Eager) {
                        var selectionControl = new UtfprFormEagerLoadEditor(controlValue);

                        if (editorService.ShowDialog(selectionControl) == DialogResult.OK) {
                            if (selectionControl.Value != null) {
                                value = selectionControl.Value;
                            }
                        }
                    } else {
                        MessageBox.Show("Just for eager fetch mode");
                    }
                }
            }
            return value;
        }

        /// <summary>
        /// No special thumbnail will be shown for the grid.
        /// </summary>
        public override bool GetPaintValueSupported(System.ComponentModel.ITypeDescriptorContext context) {
            return false;
        }
    }
}

